package com.luoying.itew.fragment;

import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.luoying.itew.R;
import com.luoying.itew.activity.MainActivity;
import com.luoying.itew.activity.MainActivityViewModel;
import com.luoying.itew.bean.UserInfo;
import com.luoying.itew.common.Constant;
import com.luoying.itew.manage.UserManage;
import com.luoying.itew.util.AppUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lufan on 2019-04-26
 * Class describe
 */
public class MineFragment extends BaseFragment {

    @BindView(R.id.tv_user_phone)
    TextView tvUserPhone;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_user_city)
    TextView tvUserCity;
    @BindView(R.id.tv_position)
    TextView tvPosition;
    @BindView(R.id.tv_version)
    TextView tvVersion;

    private MainActivityViewModel modle;

    private UserInfo userInfo;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void init() {
        super.init();
        modle = ViewModelProviders.of(getActivity()).get(MainActivityViewModel.class);
        if(UserManage.getInstance().getUserInfo()!=null){
            userInfo = UserManage.getInstance().getUserInfo();
            showUserDetail();
        }
        modle.getUserInfo().observe(this, new Observer<UserInfo>() {
            @Override
            public void onChanged(@Nullable UserInfo observeUser) {
                userInfo = observeUser;
                showUserDetail();
            }
        });
        //获取个人信息
        modle.getUserDetail();
        String version = AppUtils.getVersionName(getContext());
        tvVersion.setText(String.format("V%s",version));
    }

    private void showUserDetail(){
        if(userInfo==null){
            return;
        }
        tvUserPhone.setText(userInfo.getUserMobile());
        tvUserCity.setText(userInfo.getUserCity());
        tvUserName.setText(userInfo.getUserName());
        tvPosition.setText(TextUtils.isEmpty(userInfo.getUserPosition())?"-":userInfo.getUserPosition());
    }

    @OnClick({R.id.tv_logout,R.id.rl_app_update})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tv_logout:
                //主动退出
                ((MainActivity)getActivity()).loginOut(Constant.LOGOUT_TYPE_EXIT);
                break;
            case R.id.rl_app_update:
                modle.updateVersion();
                break;
        }
    }
}
